<?php

namespace App\Http\Controllers\Admin\Authorization;

use App\B2BProject\Admin\AdminControllerBuildTrait;
use App\B2BProject\Admin\Administrator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    use AdminControllerBuildTrait;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $administrators = Administrator::orderBy('created_at', 'desc')->paginate($request->query('pageSize'));

            $data = [];

            foreach ($administrators as $administrator) {
                $data[] = [
                    'id'        => $administrator->id,
                    'username'  => $administrator->user,
                    'email'     => $administrator->email,
                    'ip'        => $administrator->last_login_ip,
                    'logintime' => $administrator->last_login ? date('Y-m-d H:i:s', strtotime($administrator->last_login)) : 'N/A',
                    'count'     => $administrator->login_count,
                    'attribute' => call_user_func(function ($administrator) {
                        if ($role = $administrator->roles()->first()) {
                            return $role->display_name;
                        }

                        return 'N/A';
                    }, $administrator),
                    'editorurl' => route('admin.admin.edit', [$administrator->id]),
                    'deleurl'   => route('admin.admin.destroy', [$administrator->id]),
                ];
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $administrators->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $administrators->total(),
                ],
            ]);
        }

        return view('admin.authorization.admin.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.authorization.admin.edit');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return \DB::transaction(function () use ($request) {
            $administrator = new Administrator();

            $administrator->user = $request->input('user');
            $administrator->email = $request->input('email');
            $administrator->password = \Hash::make($request->input('password'));

            $administrator->save();
            $administrator->roles()->attach($request->input('role', []));

            return redirect()->route('admin.admin.index');
        });
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $admin = Administrator::findOrFail($id);

        return view('admin.authorization.admin.edit', ['admin' => $admin]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        return \DB::transaction(function () use ($request, $id) {
            $administrator = Administrator::findOrFail($id);

            $administrator->user = $request->input('user');
            $administrator->email = $request->input('email');

            if ($password =  $request->input('password')) {
                $administrator->password = \Hash::make($password);
            }

            $administrator->save();

            $administrator->roles()->sync($request->input('role', []));

            return redirect()->route('admin.admin.index');
        });
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        // 严禁删除 ID 为 1 的管理员！！
        if ($id == 1) {
            abort(403);
        }

        Administrator::findOrFail($id)->delete();

        return $this->index($request);
    }

    public function batchRemove(Request $request)
    {
        return \DB::transaction(function () use ($request) {
            $ids = $request->input('ids', []);

            foreach ($ids as $id) {
                // 严禁删除 ID 为 1 的管理员！！
                if ($id == 1) {
                    abort(403);
                    break;
                }

                Administrator::findOrFail($id)->delete();
            }

            return $this->index($request);
        });
    }
}
